﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace RevisionHelper
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.OutputEncoding = Encoding.UTF8;
			Console.WriteLine($"arguments: {string.Join(" ", args)}");
			if (args.Length < 2)
			{
				Console.WriteLine("使用方法");
				Console.WriteLine("RevisionHelper [dir] [cmd] [ignore1] [ignore2] ... [ignoren]");
				Console.WriteLine("支持的CMD：patch 针对NetRevisionTool的patch命令，执行版本号写入功能");
				Console.WriteLine("支持的CMD：restore 针对NetRevisionTool的restore命令，执行还原功能");
				Console.WriteLine("ignoreX：表示需要忽略的目录，注意，路径中包含相关数据的都会被忽略，支持多个，空格分隔");
				return;
			}

			var dir = args[0];
			var cmd = args[1];
			var ignores = args.Skip(2).ToArray();
			if (!Directory.Exists(dir))
			{
				Console.Error.WriteLine("指定的目录不存在！");
				return;
			}

			if (cmd != "patch" && cmd != "restore")
			{
				Console.Error.WriteLine("命令不支持！");
				return;
			}

			var netRevisionTool = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NetRevisionTool.exe");
			if (!File.Exists(netRevisionTool))
			{
				Console.Error.WriteLine("NetRevisionTool.exe工具不存在！");
				return;
			}

			Console.WriteLine("正在处理...");
			var total = 0;
			var files = Directory.GetFiles(dir, "*.csproj", SearchOption.AllDirectories);
			foreach (string file in files)
			{
				var skip = false;
				foreach (string s in ignores)
				{
					if (file.Contains($"{Path.DirectorySeparatorChar}{s}"))
					{
						skip = true;
						Console.WriteLine($"{file} 已经忽略...");
						break;
					}
				}

				if (skip) continue;
				ProcessProject(netRevisionTool, cmd, Path.GetDirectoryName(file));
				total++;
			}

			Console.WriteLine($"处理完毕，共计 {total} 个");
		}

		static void ProcessProject(string exe, string cmd, string dir)
		{
			Console.WriteLine($"正在处理：{dir}");
			var processStartInfo = new ProcessStartInfo(exe) { CreateNoWindow = true, UseShellExecute = false, };
			switch (cmd)
			{
				case "patch":
					processStartInfo.Arguments = $"/info /patch \"{dir}\"";
					break;
				case "restore":
					processStartInfo.Arguments = $"/restore \"{dir}\"";
					break;
			}

			var process = new Process { StartInfo = processStartInfo };
			process.Start();
			process.WaitForExit();
			if (process.ExitCode != 0)
			{
				Console.Error.WriteLine($"{dir}处理出错, exit code {process.ExitCode}！");
			}

			process.Dispose();
		}
	}
}
